package sk.stu.fei.tomsteam;

import java.awt.Dimension;

import javax.swing.Box;
import javax.swing.BoxLayout;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JSeparator;
import javax.swing.JTree;
import javax.swing.SwingConstants;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.DefaultMutableTreeNode;
import javax.swing.tree.DefaultTreeModel;
import javax.swing.tree.TreePath;
import javax.swing.tree.TreeSelectionModel;

public class TreeInPanel extends JPanel /*implements TreeSelectionListener*/ {

	private static final long serialVersionUID = 1L;
	private DefaultMutableTreeNode rootNode;
	private DefaultTreeModel treeModel;
	private JTree tree;
	
	public TreeInPanel() {
		
		initUI();
	}
	
	
	public final void initUI() {
		this.setLayout(new BoxLayout(this, BoxLayout.LINE_AXIS));
		rootNode = new DefaultMutableTreeNode("Agents");
		treeModel = new DefaultTreeModel(rootNode);
		//treeModel.addTreeModelListener(new MyTreeModelListener());
		tree = new JTree(treeModel);
		//tree.setEditable(true);
		tree.getSelectionModel().setSelectionMode(TreeSelectionModel.SINGLE_TREE_SELECTION);
		tree.setShowsRootHandles(true);
		
		JScrollPane scrollTree = new JScrollPane(tree);
		//scrollTree.setPreferredSize(new Dimension(200, 300));
		add(scrollTree);
		add(Box.createHorizontalStrut(5));
		add(new JSeparator(SwingConstants.VERTICAL));
		add(Box.createHorizontalStrut(5));
	}
	
	
	public DefaultTreeModel getCurrentTreeModel() {
		return this.treeModel;
	}
	
	
	public JTree getCurrentTree() {
		return this.tree;
	}
	
	
	/** Add child to the currently selected node. */
    public DefaultMutableTreeNode addObject(Object child) {
        DefaultMutableTreeNode parentNode = null;
        TreePath parentPath = tree.getSelectionPath();
        
        if (parentPath == null) {
            parentNode = rootNode;
        } 
        else {
            parentNode = (DefaultMutableTreeNode) (parentPath.getLastPathComponent());
        }
 
        return addObject(parentNode, child, true);
    }
 
    public DefaultMutableTreeNode addObject(DefaultMutableTreeNode parent, Object child) {
        return addObject(parent, child, false);
    }
 
    
    public DefaultMutableTreeNode addObject(DefaultMutableTreeNode parent, Object child, boolean shouldBeVisible) {
        DefaultMutableTreeNode childNode = new DefaultMutableTreeNode(child);
 
        if (parent == null) {
            parent = rootNode;
        }
     
    //It is key to invoke this on the TreeModel, and NOT DefaultMutableTreeNode
        treeModel.insertNodeInto(childNode, parent, parent.getChildCount());
 
        //Make sure the user can see the lovely new node.
        if (shouldBeVisible) {
            tree.scrollPathToVisible(new TreePath(childNode.getPath()));
        }
        return childNode;
    }

}
